package com.xuyunceng.xinlin.service;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.xuyunceng.xinlin.entity.Role;
import com.xuyunceng.xinlin.entity.User;
import com.xuyunceng.xinlin.repository.UserRepository;

@Service
public class UserService implements UserDetailsService{

	@Autowired
	private JavaMailSender mailSender;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@Autowired
	private UserRepository userRep;

	@Value("${spring.mail.username}") // 发送人的邮箱
	private String from;

	//	使用验证码登录欣欣
	public int getCode(String phone) {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(from);
		message.setTo(phone);
		message.setSubject("欣欣登录验证码");
		int a = (int) (1 + Math.random() * (999999 - 000000 + 1));
		message.setText("登录验证码: "+a);
		mailSender.send(message);
		return a; 
	}
	
	//	用户注册
	@Transactional
	public User register(User user) {
		user.setPassword(passwordEncoder.encode(user.getPassword()));
		return userRep.save(user);
	}
	
	//	id查单个用户
	public User idOneUser(Long id) {
		return userRep.getOne(id);
	}
	
	
	
	//	删除单个用户
	@Transactional
	public void delUser(Long id) {
		User user = userRep.getOne(id);
		user.setRole(new Role(7));
		userRep.save(user);
	}

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = userRep.findByUsername(username);
		if (user!=null) {
			return user;
		}else {
			return new User();
		}
	}

}